package com.example.viewmodel;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    MyViewModel myViewModel;
    TextView topTextView;
    Button topBtn,downBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        topTextView = findViewById(R.id.textView);
        topBtn = findViewById(R.id.button);
        downBtn = findViewById(R.id.button2);

//        myViewModel = ViewModelProviders.of(this).getClass(MyViewModel.class);
        myViewModel = new ViewModelProvider(this).get(MyViewModel.class);

        topBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.number++;
                topTextView.setText(String.valueOf(myViewModel.number));
            }
        });

        downBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myViewModel.number += 2;
                topTextView.setText(String.valueOf(myViewModel.number));
            }
        });

        /*
            当屏幕旋转的时候重新创建并执行此方法
            这里需要把数据重新从model里面拿出来然后赋值
        * */
        topTextView.setText(String.valueOf(myViewModel.number));

    }

}
